package com.yao.intercepter;

import com.yao.propertis.JwtProperties;
import com.yao.utils.JwtUtil;
import com.yao.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class MyIntercepter implements HandlerInterceptor {

    // 在请求处理之前进行调用（Controller方法调用之前）
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.sendError(208, "没有token");
            return false;
        }
        try {
            // 解析token
            Claims claims = JwtUtil.parseJWT(JwtProperties.secretKey, token);
            String openid = (String) claims.get("openid");
            UserContext.setUser(openid);
        } catch (Exception e) {
            response.sendError(208, "token过期或无效");
            return false;
        }
        return true;
    }

    // 在请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    // 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于清理资源）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
